//
//  GFScan.m
//  GoFactory
//
//  Created by wtb on 2017/12/22.
//  Copyright © 2017年 KQZK. All rights reserved.
//

#import "GFScan.h"
#import "WMZDialog.h"
#import <AVFoundation/AVFoundation.h>

@interface GFScan()<AVCaptureMetadataOutputObjectsDelegate>
@property(nonatomic,copy)   void(^scanBlock)(NSString *value,NSString *type);
@property(nonatomic,assign) BOOL                        isScan;
@property(nonatomic,strong) UIView                      *videoPreView;
@property(nonatomic,strong) AVCaptureDevice             *device;
@property(nonatomic,strong) AVCaptureDeviceInput        *input;
@property(nonatomic,strong) AVCaptureMetadataOutput     *output;
@property(nonatomic,strong) AVCaptureSession            *session;
@property(nonatomic,strong) AVCaptureVideoPreviewLayer  *previewLayer;
@property(nonatomic,assign) BOOL                        isBarScan;

@property (nonatomic, strong) NSArray *metadataObjectTypes;

@end

@implementation GFScan


-(instancetype)initWithPreView:(UIView *)preView isSupportBarcode:(BOOL)isSupportBarcode success:(void (^)(NSString *value,NSString *type))result
{
    if (self = [super init]) {
        self.scanBlock = result;
        self.videoPreView = preView;
        self.isBarScan = isSupportBarcode;
        [self createSession];
    }
    return self;
}

-(void)createSession
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];

    if (authStatus == AVAuthorizationStatusRestricted ||

        authStatus ==AVAuthorizationStatusDenied){
        Dialog()
            .wTypeSet(DialogTypeAuto)
            .wMessageSet(@"未开启相机权限,请求手机设置开启")
            .wStart();
//        [GFMBManager showBriefAlert:Localized(@"openPermissions", @"Public")];
        return;
    }
    [self.session setSessionPreset:[self _canSetSessionPreset]];
    [_session addInput:self.input];
    [_session addOutput:self.output];
    // 默认条形码和二维码都支持
    _output.metadataObjectTypes = self.metadataObjectTypes;

    if(!self.isBarScan){
        // 只支持扫二维码
        [self.output setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeQRCode,AVMetadataObjectTypePDF417Code,
                                             AVMetadataObjectTypeAztecCode,
                                             AVMetadataObjectTypeDataMatrixCode, nil]];
        
    }
    [self initPreviewLayer];
}

-(void)initPreviewLayer
{
    self.previewLayer =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.previewLayer.frame = self.videoPreView.bounds;
    [self.videoPreView.layer insertSublayer:self.previewLayer atIndex:0];
}

-(void)start
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
//        Dialog()
//            .wTypeSet(DialogTypeAuto)
//            .wMessageSet(@"请打开摄像头")
//            .wStart();
        return;
    }
    if (self.session != nil && self.input != nil) {
        [self performSelector:@selector(setupCamera) withObject:nil afterDelay:0.001];
//        [self.session startRunning];
    }
}

-(void)stop
{
    if (self.input && self.session.isRunning) {
        [self.session stopRunning];
    }
}

-(void)setupCamera
{
//    [self.videoPreView.layer insertSublayer:self.previewLayer atIndex:0];
    [self.session startRunning];
}

- (void)previewLayerRemoveFromSuperlayer
{
    [_previewLayer removeFromSuperlayer];
}

+(void)recognizeImage:(UIImage*)image success:(void(^)(NSArray *))block
{
    CIDetector*detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy : CIDetectorAccuracyLow}];
    NSData *imageData = UIImagePNGRepresentation(image);
    CIImage *ciImage = [CIImage imageWithData:imageData];
    NSArray *features = [detector featuresInImage:ciImage];
    NSMutableArray *mutableArray = [[NSMutableArray alloc]initWithCapacity:1];
    for (NSInteger i = 0; i < [features count]; i++)
    {
        CIQRCodeFeature *feature = [features objectAtIndex:i];
        NSString *scannedResult = feature.messageString;
        [mutableArray addObject:scannedResult];
    }
    if (block) {
        block(mutableArray);
    }
}

+ (UIImage*)createQRWithString:(NSString*)text QRSize:(CGSize)size
{
    NSData *stringData = [text dataUsingEncoding: NSUTF8StringEncoding];
    
    //生成
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    
    CIImage *qrImage = qrFilter.outputImage;
    
    //绘制
    CGImageRef cgImage = [[CIContext contextWithOptions:nil] createCGImage:qrImage fromRect:qrImage.extent];
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetInterpolationQuality(context, kCGInterpolationNone);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage);
    UIImage *codeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    CGImageRelease(cgImage);
    
    return codeImage;
}

- (AVCaptureDevice *)device {
    if (!_device) {
        _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    }
    return _device;
}
- (AVCaptureDeviceInput *)input {
    if (!_input) {
        _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    }
    return _input;
}
- (AVCaptureMetadataOutput *)output {
    if (!_output) {
        _output = [[AVCaptureMetadataOutput alloc] init];
        _output.rectOfInterest = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    }
    return _output;
}

- (AVCaptureSession *)session {
    if (!_session) {
        _session = [[AVCaptureSession alloc] init];
    }
    return _session;
}

- (NSArray *)metadataObjectTypes {
    if (!_metadataObjectTypes) {
        _metadataObjectTypes = @[
            AVMetadataObjectTypeUPCECode,
            AVMetadataObjectTypeCode39Code,
            AVMetadataObjectTypeCode39Mod43Code,
            AVMetadataObjectTypeEAN13Code,
            AVMetadataObjectTypeEAN8Code,
            AVMetadataObjectTypeCode93Code,
            AVMetadataObjectTypeCode128Code,
            AVMetadataObjectTypeInterleaved2of5Code,
            AVMetadataObjectTypeITF14Code,
            AVMetadataObjectTypePDF417Code,
            AVMetadataObjectTypeQRCode,
            AVMetadataObjectTypeAztecCode,
            AVMetadataObjectTypeDataMatrixCode,
        ];
    }
    return _metadataObjectTypes;
}

-(void)changeScanMetaTypes:(BOOL)isQr{
    if(isQr){
        [self.output setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeQRCode,AVMetadataObjectTypePDF417Code,
                                             AVMetadataObjectTypeAztecCode,
                                             AVMetadataObjectTypeDataMatrixCode, nil]];
    }else{
        [self.output setMetadataObjectTypes:@[
            AVMetadataObjectTypeUPCECode,
            AVMetadataObjectTypeCode39Code,
            AVMetadataObjectTypeCode39Mod43Code,
            AVMetadataObjectTypeEAN13Code,
            AVMetadataObjectTypeEAN8Code,
            AVMetadataObjectTypeCode93Code,
            AVMetadataObjectTypeCode128Code,
            AVMetadataObjectTypeInterleaved2of5Code,
            AVMetadataObjectTypeITF14Code,
//            AVMetadataObjectTypePDF417Code,
//            AVMetadataObjectTypeQRCode,
//            AVMetadataObjectTypeAztecCode,
//            AVMetadataObjectTypeDataMatrixCode,
        ]];
    }
}

- (NSString *)_canSetSessionPreset {
    if ([self.device supportsAVCaptureSessionPreset:AVCaptureSessionPreset3840x2160]) {
        return AVCaptureSessionPreset3840x2160;
    }
    if ([self.device supportsAVCaptureSessionPreset:AVCaptureSessionPreset1920x1080]) {
        return AVCaptureSessionPreset1920x1080;
    }
    if ([self.device supportsAVCaptureSessionPreset:AVCaptureSessionPreset1280x720]) {
        return AVCaptureSessionPreset1280x720;
    }
    if ([self.device supportsAVCaptureSessionPreset:AVCaptureSessionPreset640x480]) {
        return AVCaptureSessionPreset640x480;
    }
    if ([self.device supportsAVCaptureSessionPreset:AVCaptureSessionPreset352x288]) {
        return AVCaptureSessionPreset352x288;
    }
    if ([self.device supportsAVCaptureSessionPreset:AVCaptureSessionPresetHigh]) {
        return AVCaptureSessionPresetHigh;
    }
    if ([self.device supportsAVCaptureSessionPreset:AVCaptureSessionPresetMedium]) {
        return AVCaptureSessionPresetMedium;
    }
    
    return AVCaptureSessionPresetLow;
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSString *stringValue = nil;
    
    if ([metadataObjects count] >0)
    {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        if (self.scanBlock && !self.isScan) {
            self.scanBlock(stringValue,metadataObject.type);
            self.isScan = YES;
        }
    } else {
        return;
    }
    
}
@end
